package com.ruoyi.project.inner.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.project.inner.constant.MqttTopic;
import com.ruoyi.project.inner.dao.GardensTerminalMapper;
import com.ruoyi.project.inner.entity.GardensTerminal;
import com.ruoyi.project.inner.mqtt.MqttTemplate;
import com.ruoyi.project.inner.mqtt.constant.MqttInitializer;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Squbi
 */
@Service
public class MqttInitImpl implements MqttInitializer {

    private static final Logger LOGGER = LoggerFactory.getLogger(MqttInitImpl.class);

    @Autowired
    private GardensTerminalMapper terminalMapper;

    @Override
    public void init(MqttClient client) throws MqttException {
        //订阅SERVER
        client.subscribe(MqttTopic.SERVER_TOPIC, 2);
        LOGGER.info("subscribe topic `{}`", MqttTopic.SERVER_TOPIC);
        //订阅Terminal已有的频道
        List<GardensTerminal> gardensTerminals = terminalMapper.selectList(new QueryWrapper<>());
        for (GardensTerminal gardensTerminal : gardensTerminals) {
            client.subscribe(gardensTerminal.getTerminalMac() + MqttTopic.CALLBACK_ENDING, 2);
            LOGGER.info("subscribe topic `{}`", gardensTerminal.getTerminalMac() + MqttTopic.CALLBACK_ENDING);
        }
    }
}
